// pages/choose_hospital/index.js
const app     = getApp()
const request = require('../../utils/request.js');
const config = require('../../utils/config.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        region: '徐汇区',
        nowList:{  total: 0,
            current_page: 0,
            last_page: 1,
            data: []
        },
        card_id:0,
        region:[],
      multiArray: [],
      multiIndex: [0,0,0],
      chinaData: [],
      isTrue:false,
      lng:'',
       lat: '',
      longitude:'',
       latitude:'',
       keywords:'',
       tags_id:0,
    },
    input(e){
      this.setData({
        keywords:e.detail.value
      })
    },
    regionChange(e) {
        this.setData({
            region: e.detail.value[2]
        })
    },
    openmap(e){
        var  index = e.currentTarget.dataset.index;
        var mdata =this.data.nowList.data[index];
        console.log(mdata)
        if(mdata){
            var address=mdata.province+mdata.city+mdata.area+mdata.address;
      
            wx.openLocation({
      
              latitude:Number(mdata.lat),
              
              longitude: Number(mdata.lng),
              
              name: mdata.hospital_name,
              
              address: address,
              
              scale: 18,
              
              success: function(res) {
              
              console.log(res)
              
              },
              
              fail: function(err) {
              
              console.log(err)
              
              }
              
              })
              
              
       
        }
        },
        bindMultiPickerChange: function (e) {
          this.setData({
            isTrue:true
          })
            console.log(e)
            var move = e.detail;
            var value = move.value;
            console.log(value)
            this.setData({
                multiIndex: [value[0], value[1], value[2]]
        
              })
          
        var array=[],that =this;
        array[0]=  that.data.multiArray[0][that.data.multiIndex[0]];
        array[1]=that.data.multiArray[1][that.data.multiIndex[1]];
        array[2]=that.data.multiArray[2][that.data.multiIndex[2]];
        app.globalData.defaultCity=array[0]+','+array[1]+','+array[2];
        console.log(app.globalData.defaultCity)
        that.setData({
            'nowList.current_page': 0,
        });
        that.getCurrentHospital()
       
        },
        bindMultiPickerColumnChange: function (e) {
            console.log(e)
          var move = e.detail;
          var index = move.column;
          var value = move.value;
          if (index == 0) {
            this.setData({
              multiIndex: [value, 0, 0, 0]
            })
            this.getCity();
          }
          if (index == 1) {
            this.setData({
              "multiIndex[1]": value,
              "multiIndex[2]": 0,
            })
            this.getXian();
          }
          if (index == 2) {
            this.setData({
              "multiIndex[2]": value,
      
            })
           
          }
          var that =this;
          that.setData({
            'nowList.current_page': 0,
        });
        that.getCurrentHospital()
        },
        getSiteData: function () {
          let that = this;
          var data = {};
          wx.showLoading({
            title: '加载中',
          })
          request.requestLoading(
              "/api/address/getArea",
              {},
              'POST',
            ).then((ret) => {
              var chinaData = ret.data;
              that.data.chinaData = chinaData;
              var sheng = []; //  设置省数组
              for (var i = 0; i < chinaData.length; i++) {
                sheng.push(chinaData[i].name);
              }
              that.setData({
                "multiArray[0]": sheng
              })
              that.getCity(); // 得到市
              wx.hideLoading({
                  success: (res) => {},
                })
             
             
                this.getCitys()
        
            }).catch((err) => {
              console.error(err);
            });
         
         
        },
        getCity: function () { //  得到市
          var shengNum = this.data.multiIndex[0];
          var chinaData = this.data.chinaData;
          console.log(shengNum)
          console.log(this.data.chinaData)
          var cityData = chinaData[shengNum].children;
          var city = [];
          for (var i = 0; i < cityData.length; i++) {
            city.push(cityData[i].name)
          }
          this.setData({
            "multiArray[1]": city
          })
         this.getXian()
        },
        getXian: function (e) { //  得到县
            var shengNum = this.data.multiIndex[0];
            var cityNum = this.data.multiIndex[1];
            var chinaData = this.data.chinaData;
         
            var c=[{id: 0, pid:  chinaData[shengNum].children[cityNum].id, name: "全部"}];
            var xianData = chinaData[shengNum].children[cityNum].children;
            xianData =c.concat(xianData)
            console.log(xianData)
            var xian = [];
        
            for (var i = 0; i < xianData.length; i++) {
              xian.push(xianData[i].name)
            }
            this.setData({
              "multiArray[2]": xian
            })
         
          },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            card_id:options.card_id,
            tags_id:options.tags_id
        });
        this.getSiteData()
        // this.getCitys()
        
    },
    init_Data(){
        var that = this;
        that.setData({
            'nowList.current_page': 0,
        });
        that.getCurrentHospital()


    },
 

    goappoint(e){
       var that=this;
       var json={};
       json.card_id=that.data.card_id;
       request.requestLoading(
        "/api/mine/checkInfo",
        json,
        'POST',
      ).then((res) => {
       
       if(res.code==1){
        wx.navigateTo({
            url: '/pages/make_appointment/index?card_id='+that.data.card_id+'&hosptial_id='+e.currentTarget.dataset.id+'&tags_id='+that.data.tags_id,
          })
       }
       
       
  
      }).catch((err) => {
        console.error(err);
      });
      
    },
    godetail(e){
        var that=this;
        wx.navigateTo({
          url: '/pages/hospital_detail/index?card_id='+that.data.card_id+'&hosptial_id='+e.currentTarget.dataset.id+'&tags_id='+that.data.tags_id,
        })
    },
    getCitys(){
        var that =this;
        console.log(getApp().globalData.lat=='')
        if(getApp().globalData.lat==''){
            app.getLocation(function (res) {
                // 经度
                console.log(res)
                var lng = res.longitude
                // 纬度
                var lat = res.latitude
                that.setData({
                  lng: lng,
                  lat: lat,
                  longitude:lng,
                  latitude:lat
                })
                console.log(3322)
                that.getCurrentCitys()
               
              });
        }else{
            that.setData({
                lng: app.globalData.lng,
                lat: app.globalData.lat,
                longitude:app.globalData.lng,
                latitude:app.globalData.lat
              })
              if(app.globalData.defaultCity==''){
                that.getCurrentCitys()
              }else{
                  var citys= app.globalData.defaultCity.split(',');
                var chinaData = that.data.chinaData;
      
                var  index = that.data.multiArray[0].indexOf(citys[0]);
             
                if(index!=-1){
                    that.setData({
                        'multiIndex[0]':index
                    })
                    var cityData = chinaData[index].children;
                    var city = [];
                    for (var i = 0; i < cityData.length; i++) {
                      city.push(cityData[i].name)
                    }
                    that.setData({
                      "multiArray[1]": city
                    })
                    var  index1 = that.data.multiArray[1].indexOf(citys[1]);
                    if(index1!=-1){
                        console.log(index1)
                        that.setData({
                            'multiIndex[1]':index1,
                            isTrue:true
                        })    
                        var c=[{id: 0, pid:  chinaData[index].children[index1].id, name: "全部"}];
                        var xianData = chinaData[index].children[index1].children;
                        xianData=c.concat(xianData)
                        var xian = [];
                        for (var i = 0; i < xianData.length; i++) {
                          xian.push(xianData[i].name)
                        }
                        that.setData({
                          "multiArray[2]": xian
                        })
                        that.setData({
                            'multiIndex[2]':0
                        })
                        // var  index2 = that.data.multiArray[2].indexOf(citys[2]);
                        // if(index2!=-1){
                        //     that.setData({
                        //         'multiIndex[2]':index2
                        //     })
                           
                          
                        // }
                        that.getCurrentHospital()    
                    }
                }
              }
            
        }
       
    
    },
    getCurrentCitys(){
        var that =this;
        console.log(332244)
        var json={};
        json.city=that.data.multiArray[1][that.data.multiIndex[1]];
        json.district=that.data.multiArray[2][that.data.multiIndex[2]];
        request.requestLoading(
            "/api/distance/getCurrentCity",
            {
           lat:that.data.lat,
           lng:that.data.lng
            },
            'POST',
          ).then((ret) => {
           
           if(ret.code==1){
          
            var chinaData = that.data.chinaData;
      
            var  index = that.data.multiArray[0].indexOf(ret.data.province);
         
            if(index!=-1){
                that.setData({
                    'multiIndex[0]':index
                })
                var cityData = chinaData[index].children;
                var city = [];
                for (var i = 0; i < cityData.length; i++) {
                  city.push(cityData[i].name)
                }
                that.setData({
                  "multiArray[1]": city
                })
                var  index1 = that.data.multiArray[1].indexOf(ret.data.city);
                if(index1!=-1){
                    console.log(index1)
                    that.setData({
                        'multiIndex[1]':index1,
                        isTrue:true
                    })    
                    var c=[{id: 0, pid:  chinaData[index].children[index1].id, name: "全部"}];
                    var xianData = chinaData[index].children[index1].children;
                    xianData=c.concat(xianData)
                    var xian = [];
                    for (var i = 0; i < xianData.length; i++) {
                      xian.push(xianData[i].name)
                    }
                    that.setData({
                      "multiArray[2]": xian
                    })
                    that.setData({
                        'multiIndex[2]':0
                    })
                    // var  index2 = that.data.multiArray[2].indexOf(ret.data.district);
                    // if(index2!=-1){
                    //     that.setData({
                    //         'multiIndex[2]':index2
                    //     })
                       
                      
                    // }
                    that.getCurrentHospital()    
                }
            }
           }
         
           
           
      
          }).catch((err) => {
            console.error(err);
          });
    },
    getCurrentHospital()
{
 
    var that =this;
    var json = {};
    json.nindex=that.data.nindex;
    json.keywords=that.data.keywords;
    json.page = Number(that.data.nowList.current_page) + 1;
    json.lat=that.data.lat;
    json.lng=that.data.lng;
    json.card_id=that.data.card_id;
    json.tags_id=that.data.tags_id;
    json.city=that.data.multiArray[1][that.data.multiIndex[1]];
    json.district=that.data.multiArray[2][that.data.multiIndex[2]];
    if (json.page > 1 && that.data.nowList.current_page >= that.data.nowList.last_page) {       
        return false;
    }
    request.requestLoading(
        "/api/distance/getHospitals",
        json,
        'POST',
      ).then((res) => {
       
        var nowList = res.data;
            that.setData({
                is_show:true
            })
    
            if (json.page > 1) {
                var now_nowList_data =that.data.nowList.data || [];
                var now_nowList_data = now_nowList_data.concat(nowList.data);
                nowList.data = now_nowList_data;
            }
      
            that.setData({
              nowList: nowList
            });
    
       
       
  
      }).catch((err) => {
        console.error(err);
      });
},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.init_Data()
        setTimeout(function(){
          wx.stopPullDownRefresh();
        },500)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        var that =this;

        if (that.data.nowList.current_page >= that.data.nowList.last_page) {
          // functions.toast('已加载到底部了');
          return false;
      } else {
        that.getCurrentHospital()
      }
    },

   
})